package com.turing.post.selfwebservice.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.cardmanagement.util.ActivateCard;
import com.turing.post.cardmanagement.util.ActivateCardDao;
import com.turing.post.cardmanagement.util.MakeCardControl;
import com.turing.post.cardmanagement.util.MakeCardControlDao;
import com.turing.post.common.util.CommonRespCode;
import com.turing.post.common.util.Global;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.common.util.SysOpUser;
import com.turing.post.common.util.SysOpUserDao;
import com.turing.post.selfwebservice.util.CardHolderUser;
import com.turing.post.selfwebservice.util.CardHolderUserBusiness;
import com.turing.post.selfwebservice.util.CardHolderUserDao;
import com.turing.post.selfwebservice.util.CardHolderUserLink;
import com.turing.post.selfwebservice.util.CardHolderUserLinkDao;
import com.turing.post.selfwebservice.util.SelfWebApplicationException;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.SHA1;

/**
 * 自助服务网站业务逻辑实现类
 * 
 * @author 李治
 * 
 */
@Stateless(mappedName = "selfwebservice.impl.CardHolderUserBusinessImpl")
@Remote
@Local
public class CardHolderUserBusinessImpl implements CardHolderUserBusiness {

	@EJB(mappedName = "selfwebservice.impl.CardHolderUserDaoImpl")
	private CardHolderUserDao cardHolderUserDaoImpl;
	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao commonDaoImpl;
	@EJB(mappedName = "cardmanagement.impl.ActivateCardDaoImpl")
	private ActivateCardDao activateCardDaoImpl;
	@EJB(mappedName = "selfwebservice.impl.CardHolderUserLinkDaoImpl")
	private CardHolderUserLinkDao cardHolderUserLinkDaoImpl;
	@EJB(mappedName = "cardmanagement.impl.MakeCardControlDaoImpl")
	private MakeCardControlDao makeCardControlDaoImpl;
	@EJB(mappedName = "common.impl.SysOpUserDaoImpl")
	private SysOpUserDao sysOpUserDaoImpl;

	@Override
	public CardHolderUser CardHolderUserLogon(CardHolderUser cardHolderUser)
			throws PCPSApplicationException {
		if (null == cardHolderUser || null == cardHolderUser.getLogonName())
			errException("持卡用户登录参数为空");
		CardHolderUser oper = cardHolderUserDaoImpl
				.getCardHolderUserByLogonName(cardHolderUser.getLogonName());
		if (null == oper)
			errException("持卡用户不存在");
		if ("0".equals(oper.getStatus()))
			errException("用户已停用，禁止登录");
		Global global = commonDaoImpl.getGlobalInfo();
		if (global.getMaxPwdErrCnt() > 0) {
			if (oper.getPwdErrCnt() >= global.getMaxPwdErrCnt()) {
				// 判断是否在global登录限制时间之内，限制时间分钟
				if ((commonDaoImpl.getDatabaseSysTime().getTime() - oper
						.getLastPwdErrTime().getTime()) / 60000 < global
						.getPwdErrLimit()) {
					errException("基础数据Global表数据有误，系统管理员必须先维护参数数据!");
				}
				errException("密码输入错误次数超过" + global.getMaxPwdErrCnt()
						+ "次，系统限制登录");
			}
		}
		// 判断密码
		StringBuffer logonName = new StringBuffer(cardHolderUser.getLogonName());
		String encryptionPWD = new SHA1().getDigestOfString(logonName.append(
				cardHolderUser.getLogonPasswd().trim()).toString().getBytes());
		if (!oper.getLogonPasswd().equals(encryptionPWD)) {
			oper.setPwdErrCnt(oper.getPwdErrCnt() + 1);
			oper.setLastPwdErrTime(commonDaoImpl.getDatabaseSysTime());
			cardHolderUserDaoImpl.updateCardHolderUser(oper);
			errException("密码输入错误!");
			return null;
		} else {
			if (oper.getPwdErrCnt().compareTo(0) > 0) {
				oper.setPwdErrCnt(0);
				cardHolderUserDaoImpl.updateCardHolderUser(oper);
			}
			CardHolderUser returnUser = getCardHolderUserByCardHolderUserId(oper
					.getCardHolderUserId());
			return returnUser;
		}
	}

	@Override
	public CardHolderUser getCardHolderUserByCardHolderUserId(
			BigInteger cardHolderUserId) {
		return cardHolderUserDaoImpl
				.getCardHolderUserByCardHolderUserId(cardHolderUserId);
	}

	@Override
	public List<CardHolderUser> getCardHolderUsers(Integer page) {
		return cardHolderUserDaoImpl.getCardHolderUsers(page);
	}

	@Override
	public List<CardHolderUser> getCardHolderUsersByCondition(String email,
			String name, Integer idTypeId, String idNo, String sex,
			String status, Integer page) {
		return cardHolderUserDaoImpl.getCardHolderUsersByCondition(email, name,
				idTypeId, idNo, sex, status, page);
	}

	@Override
	public Integer getCardHolderUsersCount() {
		return cardHolderUserDaoImpl.getCardHolderUsersCount();
	}

	@Override
	public Integer getCardHolderUsersCountByCondition(String email,
			String name, Integer idTypeId, String idNo, String sex,
			String status) {
		return cardHolderUserDaoImpl.getCardHolderUsersCountByCondition(email,
				name, idTypeId, idNo, sex, status);
	}

	@Override
	public void getLossPassword(CardHolderUser cardHolderUser)
			throws PCPSApplicationException {
		if (null == cardHolderUser)
			errException("参数cardHolderUser为空");
		CardHolderUser _CardHolderUser = cardHolderUserDaoImpl
				.getCardHolderUserByLogonName(cardHolderUser.getLogonName());
		if (null == _CardHolderUser)
			errException("持卡用户不存在");
		// 有一个答案正确时找回密码
		if (_CardHolderUser.getAnswer1().equals(cardHolderUser.getAnswer1())
				|| _CardHolderUser.getAnswer2().equals(
						cardHolderUser.getAnswer2())
				|| _CardHolderUser.getAnswer3().equals(
						cardHolderUser.getAnswer3())) {
			StringBuffer news = new StringBuffer(cardHolderUser.getLogonName());
			String newPwd = new SHA1().getDigestOfString(news.append(
					cardHolderUser.getLogonPasswd().trim()).toString()
					.getBytes());
			_CardHolderUser.setLogonPasswd(newPwd);
			_CardHolderUser.setPwdErrCnt(0);
			_CardHolderUser.setLastPwdChangeTime(commonDaoImpl
					.getDatabaseSysTime());
			// 修改
			cardHolderUserDaoImpl.updateCardHolderUser(_CardHolderUser);
		} else {
			errException("所有安全问题答案都为空!");
		}
	}

	@Override
	public void insertCardHolderUser(CardHolderUser cardHolderUser,
			String cardNo, String cardPwd) throws PCPSApplicationException {
		if (null == cardHolderUser)
			errException("持卡用户参数为空");
		if (PCPSUtil.isEmpty(cardHolderUser.getLogonName()))
			errException("登录名不能为空");
		if (cardHolderUser.getLogonName().trim().length() < 6)
			errException("登录名长度不能小于6位");
		CardHolderUser user = cardHolderUserDaoImpl
				.getCardHolderUserByLogonName(cardHolderUser.getLogonName());
		if (null != user)
			errException("该登录名 [ " + user.getLogonName() + " ] 已存在");
		if (null == cardHolderUser.getEmail())
			errException("邮箱不能为空");
		// 检测邮箱是否已被注册
		if (cardHolderUserDaoImpl.checkEmailAlreadyRegister(cardHolderUser
				.getEmail()))
			errException("Email [ " + cardHolderUser.getEmail() + " ] 已被注册");
		ActivateCard activateCard = activateCardDaoImpl
				.getActivateCardByCardNo(cardNo);
		if (null == activateCard) {
			errException("卡号为 [" + cardNo + "] 卡不存在或暂未被激活");
		}
		if (cardHolderUserLinkDaoImpl.checkCardLinked(cardNo))
			errException("卡号为 [" + cardNo + "] 的卡已被关联");
		if (!activateCard.VerifyPassword(cardPwd)) {
			errException("卡号与密码不匹配");
		}
		cardHolderUser.setStatus("1");
		cardHolderUser.setPwdErrCnt(0);
		StringBuffer news = new StringBuffer(cardHolderUser.getLogonName());
		String encryptionPWD = new SHA1().getDigestOfString(news.append(
				cardHolderUser.getLogonPasswd().trim()).toString().getBytes());
		cardHolderUser.setLogonPasswd(encryptionPWD);
		cardHolderUser.setLastPwdChangeTime(commonDaoImpl.getDatabaseSysTime());
		BigInteger cardHolderUserId = cardHolderUserDaoImpl
				.getMaxCardHolderUserId();// 主键ID
		cardHolderUser.setCardHolderUserId(cardHolderUserId);
		cardHolderUserDaoImpl.insertCardHolderUser(cardHolderUser);
		CardHolderUserLink cardHolderUserLink = new CardHolderUserLink();
		cardHolderUserLink.setCardHolderUserId(cardHolderUserId);
		cardHolderUserLink.setCardNo(cardNo);
		cardHolderUserLinkDaoImpl.insertCardHolderUserLink(cardHolderUserLink);
	}

	@Override
	public List<CardHolderUserLink> getCardHolderUserLinksByCardHolderUserId(
			BigInteger cardHolderUserId) {
		return cardHolderUserLinkDaoImpl
				.getCardHolderUserLinksByCardHolderUserId(cardHolderUserId);
	}

	@Override
	public void insertCardHolderUserLink(CardHolderUserLink cardHolderUserLink,
			String cardPwd) throws PCPSApplicationException {
		if (null == cardHolderUserLink)
			errException("持卡用户关联卡参数为空");
		if (null == cardHolderUserLink.getCardHolderUserId())
			errException("持卡用户ID不能为空");
		if (null == cardHolderUserLink.getCardNo())
			errException("卡号不能为空");
		if (null == cardPwd)
			errException("卡密码不能为空");
		if (cardHolderUserLinkDaoImpl.checkCardLinked(cardHolderUserLink
				.getCardNo()))
			errException("卡号为 [" + cardHolderUserLink.getCardNo() + "] 的卡已被关联");
		CardHolderUser chu = getCardHolderUserByCardHolderUserId(cardHolderUserLink
				.getCardHolderUserId());
		if (null == chu || "0".equals(chu.getStatus()))
			errException("持卡用户不存在或已停用");
		ActivateCard activateCard = activateCardDaoImpl
				.getActivateCardByCardNo(cardHolderUserLink.getCardNo());
		if (null == activateCard)
			errException("卡号为 [" + cardHolderUserLink.getCardNo()
					+ "] 卡不存在或暂未被激活");
		if (!activateCard.VerifyPassword(cardPwd))
			errException("卡号与密码不匹配");
		cardHolderUserLinkDaoImpl.insertCardHolderUserLink(cardHolderUserLink);
	}

	@Override
	public void cancelCardHolderUserLink(CardHolderUserLink cardHolderUserLink)
			throws PCPSApplicationException {
		if (null == cardHolderUserLink)
			errException("持卡用户关联卡参数为空");
		if (null == cardHolderUserLink.getCardHolderUserId())
			errException("持卡用户ID不能为空");
		if (null == cardHolderUserLink.getCardNo())
			errException("卡号不能为空");
		List<CardHolderUserLink> cardHolderUserLinks = cardHolderUserLinkDaoImpl
				.getCardHolderUserLinksByCardHolderUserId(cardHolderUserLink
						.getCardHolderUserId());
		if (cardHolderUserLinks.size() <= 1)
			errException("持卡用户至少需要关联一张卡");
		cardHolderUserLinkDaoImpl.deleteCardHolderUserLink(cardHolderUserLink);
	}

	@Override
	public void changeCardHolderUserPwd(CardHolderUser cardHolderUser,
			String newPassWord) throws PCPSApplicationException {
		if (null == cardHolderUser)
			errException("参数CardHolderUser为空");
		if (PCPSUtil.isEmpty(newPassWord))
			errException("新密码为空");
		if (PCPSUtil.isEmpty(cardHolderUser.getLogonName()))
			errException("持卡用户登录名为空");
		if (PCPSUtil.isEmpty(cardHolderUser.getLogonPasswd())) {
			errException("原始密码不能为空");
		}
		CardHolderUser _CardHolderUser = cardHolderUserDaoImpl
				.getCardHolderUserByCardHolderUserId(cardHolderUser
						.getCardHolderUserId());
		if (null == _CardHolderUser)
			errException("持卡用户不存在");
		// 用户输入的旧密码
		String oldPwd = new SHA1().getDigestOfString((cardHolderUser
				.getLogonName() + cardHolderUser.getLogonPasswd()).getBytes());
		if (!oldPwd.equals(_CardHolderUser.getLogonPasswd()))// 输入旧密码与数据库中就密码不相等
			errException("原始密码输入错误");
		// 新密码
		String newPwd = new SHA1().getDigestOfString((cardHolderUser
				.getLogonName() + newPassWord).getBytes());
		_CardHolderUser.setLogonPasswd(newPwd);
		_CardHolderUser.setPwdErrCnt(0);
		_CardHolderUser
				.setLastPwdChangeTime(commonDaoImpl.getDatabaseSysTime());
		cardHolderUserDaoImpl.updateCardHolderUser(_CardHolderUser);
	}

	@Override
	public CardHolderUser getCardHolderUserQuestionByLogonName(String logonName) {
		return cardHolderUserDaoImpl
				.getCardHolderUserQuestionByLogonName(logonName);
	}

	@Override
	public void updateCardHolderUser(CardHolderUser cardHolderUser)
			throws PCPSApplicationException {
		if (null == cardHolderUser)
			errException("持卡用户参数为空");
		CardHolderUser user = cardHolderUserDaoImpl
				.getCardHolderUserByCardHolderUserId(cardHolderUser
						.getCardHolderUserId());
		if (null == user)
			errException("持卡用户不存在");
			user.setName(cardHolderUser.getName());
			user.setSex(cardHolderUser.getSex());
			user.setLinkTele(cardHolderUser.getLinkTele());
			user.setMobile(cardHolderUser.getMobile());
			user.setAddr(cardHolderUser.getAddr());
			user.setQuestion1(cardHolderUser.getQuestion1());
			user.setAnswer1(cardHolderUser.getAnswer1());
			user.setQuestion2(cardHolderUser.getQuestion2());
			user.setAnswer2(cardHolderUser.getAnswer2());
			user.setQuestion3(cardHolderUser.getQuestion3());
			user.setRemark(cardHolderUser.getRemark());
			user.setAnswer3(cardHolderUser.getAnswer3());
		cardHolderUserDaoImpl.updateCardHolderUser(cardHolderUser);
	}

	/**
	 * 异常抛出方法
	 * 
	 * @param error
	 * @throws PCPSApplicationException
	 */
	private void errException(String error) throws PCPSApplicationException {
		throw new SelfWebApplicationException(
				SelfWebApplicationException.ERRCODE_CATEGORY_APPLICATION,
				CommonRespCode.USERLOGON, error);
	}

	@Override
	public SysOpUser getInternetAgentSysOpUserByCardNo(String cardNo) {
		if (PCPSUtil.isEmpty(cardNo)) {
			return null;
		}
		ActivateCard ac = activateCardDaoImpl.getActivateCardByCardNo(cardNo);
		if (ac == null) {
			return null;
		} else {
			MakeCardControl mcc = makeCardControlDaoImpl
					.getMakeCardControlByBatchNo(ac.getBatchNo());
			SysOpUser sou = sysOpUserDaoImpl
					.getInternetAgentSysOpUserByIssueCompany(mcc
							.getIssueCompanyNo());
			return sou;
		}
	}
}
